import puppeteer from 'puppeteer'
// import * as puppeteer from 'puppeteer'
import { app } from 'electron'

// const puppeteer = require('puppeteer')
const path = require('path')
const fs = require('fs')
// const { remote } = require('electron');

async function launchChrome() {
  const args = [
    '--disable-features=site-per-process,TranslateUI',
    '--start-maximized',
    '--disable-dev-shm-usage',
    '--memory-pressure-off',
    '--disable-blink-features=AutomationControlled',
    '--disable-infobars',
    '--no-first-run',
    '--disable-background-networking'
  ]

  // 创建一个chrome实例
  const chrome = await puppeteer.launch({
    executablePath:
      process.env.NODE_ENV === 'development'
        ? path.join(app.getAppPath(), 'bundled\\chrome\\win64-1056772\\chrome-win\\chrome.exe')
        : path.join(app.getAppPath(), '../', 'chrome\\win64-1056772\\chrome-win\\chrome.exe'),
    defaultViewport: null,
    ignoreDefaultArgs: true,
    args: args
  })
  return chrome
}

// const chrome = await puppeteer.launch({
//   executablePath:
//     process.env.NODE_ENV === 'development'
//       ? path?.join(app.getAppPath(), 'bundled\\chrome\\win64-1056772\\chrome-win\\chrome.exe')
//       : path?.join(app.getAppPath(), '../', 'chrome\\win64-1056772\\chrome-win\\chrome.exe'),
//   defaultViewport: null,
//   ignoreDefaultArgs: true,
//   args: args

/**
 * @returns 返回一个随机数 3000-6000
 */
export function randomNumOneToFive() {
  return Math.floor(Math.random() * 3 + 3) * 1000
}

// async function removeWebdriver(page: puppeteer.Page): Promise<void> {
//   await page.evaluateOnNewDocument(() => {
//     const newProto = navigator.__proto__
//     delete newProto.webdriver
//     navigator.__proto__ = newProto
//   })
// }

export function sleep(time = 1500) {
  return new Promise((resolve) => {
    let timer = setTimeout(
      () => {
        clearTimeout(timer)
        resolve('')
      },
      time + 1000 * Math.random()
    )
  })
}

async function removeWebdriver(page: any): Promise<void> {
  await page.evaluate(() => {
    Object.defineProperty(navigator, 'webdriver', {
      get: () => false
    })
  })
}

// async function setCookie(page: puppeteer.Page, cookieName: string): Promise<void> {
//   const userDataPath = app.getPath('userData')
//   const cookiesFilePath = path.join(userDataPath, `data/cookies_${cookieName}.json`)
//   if (fs.existsSync(cookiesFilePath)) {
//     const cookies = JSON.parse(fs.readFileSync(cookiesFilePath, 'utf8'))
//     for (const cookie of cookies) {
//       await page.setCookie(cookie)
//     }
//   }
// }

async function setCookie(page: any, cookieName: string): Promise<void> {
  const cookiesFilePath = path.join(process.env.COOKIEPATH as string, `${cookieName}.json`)
  if (fs.existsSync(cookiesFilePath)) {
    const cookies = JSON.parse(fs.readFileSync(cookiesFilePath, 'utf8'))
    for (const cookie of cookies) {
      await page.setCookie(cookie)
    }
  }
}

async function writeCookie(page: any, cookieName: string): Promise<void> {
  const pageCookies = await page.cookies()
  const cookiesFilePath = path.join(process.env.COOKIEPATH as string, `${cookieName}.json`)
  fs.writeFileSync(cookiesFilePath, JSON.stringify(pageCookies))
}

/**
 * @description 保存数据到本地
 * @param data
 */
function setData(data: any) {
  const fileName = 'Tabledata'
  const userDataPath = path.join(process.env.ELECTRONDATAPATH as string, `${fileName}.json`)
  if (!fs.existsSync(userDataPath)) {
    fs.mkdirSync(path.dirname(userDataPath), { recursive: true })
  }
  fs.writeFileSync(userDataPath, JSON.stringify(data))
}

/**
 * @description 从本地获取数据
 * @returns  返回数据
 */
function getData() {
  const fileName = 'Tabledata'
  const userDataPath = path.join(process.env.ELECTRONDATAPATH as string, `${fileName}.json`)
  const pureTabledata = fs.existsSync(userDataPath) ? fs.readFileSync(userDataPath, 'utf8') : []
  return pureTabledata
}

export { launchChrome, removeWebdriver, setCookie, writeCookie, setData, getData }
